<template>
	<el-button size="mini" @click="int">导入题目</el-button>
  <el-dialog
    v-loading.fullscreen="isLoading"
    v-model="modal1"
    element-loading-text="导入中..."
    title="导入试题"
    class="customdialog"
    :width="800"
	 :close-on-click-modal="false"
  >
    <el-row>
      <h2 align="center" class="mb20 f18" style='width: 100%;margin-bottom: 25px;'>请严格按照示例文件格式导入</h2>
    </el-row>
    <el-row>
      <p style="margin:5px 0 !important;color:#999;font-size:12px;">示例文件内试题类型和难度对应相应编号的说明：</p>
    </el-row>
    <!-- <el-row>
      <p
        style="margin:5px 0 !important;color:#999;font-size:12px;"
      >一、试题类型：<span class="">1、单选</span> <span class="ml10">2、多选</span> <span class="ml10">3、判断</span> <span class="ml10">4、填空题</span> <span class="ml10">5、简答题</span> <span class="ml10">6、定值填空</span></p>
    </el-row> -->
    <el-row>
      <p
        style="margin:5px 0 !important;color:#999;font-size:12px;"
      >一、试题类型：<span class="">1、单选</span> <span class="ml10">2、多选</span> <span class="ml10">3、判断</span></p>
    </el-row>
    <!-- <el-row>
      <p style="margin:5px 0 !important;color:#999;font-size:12px;">二、试题难度：<span class="ml10">1、较易</span> <span class="ml10">2、中等</span> <span class="ml10">3、较难</span></p>
    </el-row> -->
    <el-row>
      <p style="margin:5px 0 !important;color:#999;font-size:12px;">三、类型为单选题和多选题，选项不需要加字母ABCD</p>
    </el-row>
    <el-row>
      <p style="margin:5px 0 !important;color:#999;font-size:12px;">四、类型为判断题，不需要输入选项</p>
    </el-row>
    <el-row>
      <p style="margin:5px 0 !important;color:#999;font-size:12px;">五、答案内字母需大写，多选题多个答案用英文逗号隔开</p>
    </el-row>
    <el-row style="margin-top:20px;display: flex;align-items: center;">
		<UploadExcel :loadingstatus='isLoading' :onSuccess="importHander" class="mt10"></UploadExcel>
		<el-button
			type="text"
			class="mr15"
			style='margin-left: auto;'
			@click="downloadHander(template)"
		>下载示例文件</el-button>
    </el-row>
    <template #footer>
      <el-button @click="modal1 = false">关闭</el-button>
    </template>
    <el-dialog v-model="modal2" title="导入失败列表" width="600px" append-to-body :close-on-click-modal="false">
      <el-table :data="error_list">
        <el-table-column align="left" label="所在行" prop="number">
          <template #scope="scope">
            <span style="font-size: 12px">第{{scope.row.number}}行</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="错误原因" prop="detail">
          <template #scope="scope">
            <span style="font-size: 12px">{{scope.row.detail}}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </el-dialog>
</template>
<script>
import UploadExcel from "./upload";
import download from "downloadjs";
export default {
    name: "import",
    components: {
        UploadExcel,
        download
    },
    props: ['bank_id'],
    data() {
        return {
            headers: {
                Authorization: this.$TOOL.data.get("B_TOKEN")
            },
            uploadUrl: process.env.VUE_APP_BASE_API + "admin/upload/create/excel",
            modal1: false,
            modal2: false,
            isLoading: false,
            template: "https://site-1309565630.cos.ap-chongqing.myqcloud.com/template/%E5%AF%BC%E5%85%A5%E9%A2%98%E7%9B%AE%E6%A8%A1%E6%9D%BF.xlsx",
            src: "",
            error_list: [],
            category_id: [],
            categories: [],
            importQuestions: []
        };
    },
    computed: {
        time() {
            return new Date().getTime();
        }
    },
    mounted() {
    },
    methods: {
        int() {
            this.category_id = []
            this.modal1 = true;
			      this.isLoading = false
            this.src = "";
            this.importQuestions = []
        },
        handleSuccess(res) {
            this.$notify.success("上传成功");
            this.src = res.data.path;
        },
        exports() {},
        async importHander(data) {
          this.isLoading = true
          await this._importHander(data, 1)
          if (this.error_list.length > 0) {
            this.modal1 = false;
            this.modal2 = true; 
          } else {
            this.modal1 = false;
            this.modal2 = false; 
            this.$emit('success', this.importQuestions)
            this.$notify.success("导入成功");
          }

          this.isLoading = false
        },
        async _importHander(data, gloadIndex = 1) {
            this.isLoading = true;
            if (gloadIndex === 1) {
                this.error_list = [];
            }
           
            let column = {
                题目: "stem",
                选项: "A",
                __EMPTY: "B",
                __EMPTY_1: "C",
                __EMPTY_2: "D",
                __EMPTY_3: "E",
                __EMPTY_4: "F",
                __EMPTY_5: "G",
                参考答案: "corrects",
                解析: "analysis",
                题型: "type",
                // 难度系数: "difficulty"
            };
            let _optipns = ["A", "B", "C", "D", "E", "F", "G"];
            data.results.forEach(async (ele, index) => {
                if (index > 0 && gloadIndex === index) {
                    let optionData = [];
                    let _data = {};
                    for (let c in column) {
                        if (ele[c]) {
                            let isOption = false;
                            _optipns.forEach(ele => {
                                if (ele === column[c]) {
                                    isOption = true;
                                }
                            });
                            if (isOption) {
                                optionData.push({
                                    prefix: column[c],
                                    content: ele[c],
                                    type: 1
                                });
                            } else {
                                _data[column[c]] = ele[c];
                            }
                        }
                    }
                    if (_data.type === 3) {
                        if (_data.corrects !== "正确" && _data.corrects !== "错误") {
                            this.error_list.push({
                                number: index + 2,
                                detail: "判断题答案必须是“正确”或“错误”"
                            });
                            this._importHander(data, gloadIndex + 1);
                            return;
                        } else if (_data.corrects === "正确") {
                            _data.corrects = "1";
                        } else {
                            _data.corrects = "0";
                        }
                    }
                    if (_data.corrects) {
                      _data.rightAnswer = _data.corrects.split(",")
                      if(_data.type == 4){
                        _data.rightAnswer = _data.corrects.split("]")
                        let reqArr = []
                        _data.rightAnswer.forEach(item => {
                            let subArr = []
                            item = item.substr(item.indexOf('[') + 1, item.length)
                            let tA = item.split(",")
                            if (tA.length) {
                              tA.forEach(ele => {
                                  if (ele.trim().length > 0) {
                                    subArr.push(ele.trim())
                                  }
                              }) 

                              if (subArr.length) {
                                reqArr.push(subArr)     
                              } 
                            }
                        })
                        _data.rightAnswer = reqArr
                      }
                    }
                    _data.option = optionData;
                    _data.showhint = false
                    _data.hint = true
                    if(!_data.analysis){
                      _data.analysis = ''
                    }
                    _data.analysisFile = []
                    
                    if(this.error_list.length == 0){
                      this.importQuestions.push(_data)
                      this._importHander(data, gloadIndex + 1);
                    }else {
                      this.isLoading = false;
                      this.error_list.push({
                          number: index + 2,
                          detail: res.message
                      });
                      this._importHander(data, gloadIndex + 1);
                    }  
                }
            });

            this.isLoading = false;
        },
        downloadHander(url) {
            let x = new XMLHttpRequest();
            x.open( "GET", url, true);
            x.responseType = "blob"
            x.onload = () => {
                download(x.response, '导入题目模板.xlsx')
            };
            x.send();
        }
    }
};
</script>

<style scoped>
p {
  margin: 10px 0 !important;
}
</style>
